package com.example.farmer.Database;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.example.farmer.Entity.User;

import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;


public class UserMessage extends SQLiteOpenHelper {
    private static final String DB_Name = "user_db" ;
    private static final int DB_Version = 1 ;

    public UserMessage(@Nullable Context context) {
        super(context, DB_Name, null, DB_Version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_TABLE = "CREATE TABLE users (" +
                "userName TEXT NOT NULL," +
                "userNumber TEXT NOT NULL PRIMARY KEY," +
                "password TEXT NOT NULL," +
                "sex TEXT ," +
                "email TEXT ," +
                "paypassword TEXT )" ;
        db.execSQL(CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
       db.execSQL("DROP TABLE IF EXISTS users");
       onCreate(db);
    }

    @SuppressLint("Range")
    public User getUser( String userNumber,String password){
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query("users" ,
                new String[]{"userNumber" ,"password"},
                " userNumber =? AND password =?" ,
                new String[]{userNumber,password},
                null , null , null , null
                );
        User user = null ;
        if (cursor != null && cursor.moveToFirst()){
            user = new User(
                    cursor.getString(cursor.getColumnIndex("userNumber")),
                    cursor.getString(cursor.getColumnIndex("password"))
            );
            cursor.close();

        }
        return user;
    }

    public long insertUser(User user){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues() ;
        contentValues.put("userName" , user.getUserName());
        contentValues.put("userNumber" ,user.getUserNumber() );
        contentValues.put("password" , user.getPassword());
        contentValues.put("sex" , user.getSex());
        contentValues.put("email" , user.getEmail());
        contentValues.put("paypassword" , user.getPaypassword());
        long users = db.insert("users" ,null , contentValues) ;
        return users ;
    }
    //通过查询Number是否存在和修改语句来实现登录密码的修改
    public String getPasswordByStudentNumber(String userNumber){
        SQLiteDatabase db = getReadableDatabase();
        String query = "SELECT password FROM users WHERE userNumber = ?";
        Cursor cursor = db.rawQuery(query,new String[]{userNumber});
        if (cursor !=null && cursor.moveToFirst()){
            @SuppressLint("Range") String password = cursor.getString(cursor.getColumnIndex("password"));
            cursor.close();
            return password ;
        }
        return null ;
    }
    public boolean updatePassword(String userNumber, String newPassword) {
        SQLiteDatabase db = getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("password", newPassword);
        int rowsAffected = db.update("users", values, "userNumber = ?", new String[]{userNumber});
        return rowsAffected > 0;
    }


    //通过查询Number是否存在和修改语句来实现支付密码的修改
    public String getPayPasswordByStudentNumber(String userNumber){
        SQLiteDatabase db = getReadableDatabase();
        String query = "SELECT paypassword FROM users WHERE userNumber = ?";
        Cursor cursor = db.rawQuery(query,new String[]{userNumber});
        if (cursor !=null && cursor.moveToFirst()){
            @SuppressLint("Range") String paypassword = cursor.getString(cursor.getColumnIndex("paypassword"));
            cursor.close();
            return paypassword ;
        }
        return null ;
    }
    public boolean updatePayPassword(String userNumber, String newpaypassword) {
        SQLiteDatabase db = getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("paypassword", newpaypassword);
        int rowsAffected = db.update("users", values, "userNumber = ?", new String[]{userNumber});
        return rowsAffected > 0;
    }
    //查询个人信息
    public User getUserByNumber(String userNumber) {
        SQLiteDatabase db = this.getReadableDatabase();
        String query = "SELECT userName ,userNumber,password ,sex ,email , paypassword FROM users WHERE userNumber = ?";
        Cursor cursor = db.rawQuery(query, new String[]{userNumber});
        User user = null;
        if (cursor.moveToFirst()) {
            String userName = cursor.getString(cursor.getColumnIndexOrThrow("userName"));
            String password = cursor.getString(cursor.getColumnIndexOrThrow("password"));
            String sex = cursor.getString(cursor.getColumnIndexOrThrow("sex"));
            String email = cursor.getString(cursor.getColumnIndexOrThrow("email"));
            String paypassword = cursor.getString(cursor.getColumnIndexOrThrow("paypassword"));

            // 使用所有字段创建User对象
            user = new User(userName,userNumber, password, sex, email, paypassword);
        }
        cursor.close();
        db.close(); // 确保关闭数据库
        return user;
    }
    @SuppressLint("Range")
    public List<User> getAllUser(){
        List<User> user = new ArrayList<>();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query("users" , new String[]{"userNumber" , "password" } ,
                null , null , null , null ,null);
        if (cursor != null && cursor.moveToFirst()){
            do {
                 String userNumber = cursor.getString(cursor.getColumnIndex("userNumber"));
                String password = cursor.getString(cursor.getColumnIndex("password"));
                user.add(new User(userNumber,password));
            }while (cursor.moveToNext());
        }
        if (cursor != null){
            cursor.close();
        }
        db.close();

        return user ;
    }

    public boolean deleteUser(String userNumber) {
        SQLiteDatabase db = this.getWritableDatabase();
        String whereClause = "userNumber = ?";
        String[] whereArgs = { userNumber };
        int rowsDeleted = db.delete("users", whereClause, whereArgs);
        db.close();

        return rowsDeleted >0 ;
    }

    public boolean updateUser(User user) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("userName", user.getUserName()); // 更新姓名

        // 假设我们通过userNumber来定位记录
        String whereClause = "userNumber = ?";
        String[] whereArgs = { user.getUserNumber() };

        int rowsAffected = db.update("users", values, whereClause, whereArgs);
        db.close(); // 更新完成后关闭数据库

        return rowsAffected > 0; // 如果受影响的行数大于0，则表示更新成功
    }

    // 从数据库获取支付密码的方法
    public String getPayPassword(String userNumber) {
        SQLiteDatabase db = this.getReadableDatabase();
        String query = "SELECT paypassword FROM users WHERE userNumber = ?";
        Cursor cursor = db.rawQuery(query, new String[]{userNumber});
        if (cursor != null && cursor.moveToFirst()) {
            @SuppressLint("Range") String paypassword = cursor.getString(cursor.getColumnIndex("paypassword"));
            cursor.close();
            return paypassword;
        }
        return null;
    }

}
